var urllib  = require('url');
var request = require('request');
var _ = require('lodash');
var loginRes = require('./sec.js');
var aliyun = "http://pool-management.poolgpu.com:18081";
var rdserver = "http://192.168.0.100:8080";
var apiServe = aliyun;


var ALLOW_HOSTNAME = [
  '127.0.0.1:5000', '192.168.0.121:5000', 'admin.poolgpu.com:5000'
];
exports.proxy = function (req, res, next) {
  var hostname = req.headers && req.headers.host;
  var remethod = req.method;
  if(req.body && req.body.requestType) remethod = req.body.requestType;

  /*if (ALLOW_HOSTNAME.indexOf(hostname) === -1) {
    return res.send(hostname + ' is not allowed');
  }*/
  if(req.url && (req.url=="/loginpage?f=login")) {
    if(!(req.cookies&&req.cookies.sid&&(req.cookies.sid==loginRes.mn))) {
      res.send({
        code: -4,
        msg: "please login"
      });
    } else {
      res.send({
        code: 0,
        msg: "login"
      });
    }
    return;
  }
  if(req.url && (req.url=="/checklogin")) {
    if(!(req.cookies&&req.cookies.sid&&(req.cookies.sid==loginRes.mn))) {
      res.send({
        code: -3,
        msg: "please login"
      });
    } else {
      res.send({
        code: 0,
        msg: "login"
      });
    }
    return;
  }
  if(req.url && (req.url=="/login")) {
    if(req.body) {
      if((req.body.username==loginRes.n) && (req.body.password==loginRes.p)) {
        res.cookie("sid", loginRes.mn);
        res.send({
          code: 0,
          msg: "login"
        });
        return;
      } else {
        res.send({
          code: -1,
          msg: "用户名或密码错误"
        });
        return;
      }
    } else {
      res.send({
        code: -3,
        msg: "please login"
      });
      return;
    }
  }
  if((!req.cookies.sid) || (req.cookies.sid!=loginRes.mn)) {
    res.send({
      code: -3,
      msg: "please login"
    });
    return;
  }

  request({
      url: (apiServe + req.url),
      method: remethod,
      headers: {
        cookie: req.headers.cookie
      },
      json: req.body
    }, function (err, resp, body) {
      res.send(body);
    })
};